<?php

namespace app\lnk\controller;

use app\lnk\model\CircleModel;
use app\lnk\model\MessageModel;
use app\lnk\model\CircleFansModel;

use lite\controller\Backend;
use lite\controller\traits\Crud;
use think\facade\Db;
use think\Request;

class Circle extends Backend
{
    use Crud;

    public function initialize()
    {
        $this->model = new CircleModel();
    }

    public function index(Request $request)
    {
        $params = $request->get();

        if (!empty($request->param('page_size'))) {       // 使用分页
            $query = $this->model;
            if ($params['name']) $query = $query->where('name', 'like', '%' . $params['name'] . '%');
            if ($params['type'] >= 0) $query = $query->where('type', $params['type']);
            if ($params['status'] >= 0) $query = $query->where('status', $params['status']);

            $list = $query->order('status', 'asc')->order('weigh', 'desc')->order('id', 'desc')->paginate($request->param('page_size', 10));
        } else {
            $list = $this->model->order('status', 'asc')->order('weigh', 'desc')->order('id', 'desc')->select();               // 查询全部
        }


        return success('获取成功', $list);
    }

    public function update(Request $request)
    {
        $params = $request->all();
        // 发送驳回消息通知用户
        if ($params['status'] == 2 && $params['reason']) {
            $content = "驳回原因：" . $params['reason'] . "；您可以编辑后重发布";
            $content_url = '/pages/circle/add?id=' . $params['id'];
            (new MessageModel())->send($params['user_id'], '圈子被驳回', $content, 1, $params['avatar'] ?? '', '', $content_url);
        }
        $this->model->where('id', $params['id'])->update([
            'avatar' => $params['avatar'],
            'name' => $params['name'],
            'intro' => $params['intro'],
            'weigh' => $params['weigh'],
            'highlight' => $params['highlight'],
            'type' => $params['type'],
            'status' => $params['status'],
        ]);
        return success('保存成功');
    }


    public function delete($id)
    {
        $pk = $this->model->getPk();

        $result = Db::transaction(function () use ($id, $pk) {
            $count = 0;
            foreach ($this->model->whereIn($pk, $id)->cursor() as $row) {
                $count += $row->delete();
                // 删除用户关注的圈子
                CircleFansModel::where('circle_id',$id)->delete();
            }
            return $count;
        });
        if ($result) {
            return success('删除成功', $result);
        }
        return error('删除失败');
    }

}
